//
// Created by admin on 2021/4/20.
// @author 梦小星
//

#include "Explode.h"
#include <string.h>
#include <stdlib.h>

//返回一个 char *arr[], size为返回数组的长度
char **explode(char sep, const char *str, int *size) {
    int count = 0, i;
    for (i = 0; i < strlen(str); i++) {
        if (str[i] == sep) {
            count++;
        }
    }

    char **ret = static_cast<char **>(calloc(++count, sizeof(char *)));

    int lastindex = -1;
    int j = 0;

    for (i = 0; i < strlen(str); i++) {
        if (str[i] == sep) {
            ret[j] = static_cast<char *>(calloc(i - lastindex, sizeof(char))); //分配子串长度+1的内存空间
            memcpy(ret[j], str + lastindex + 1, i - lastindex - 1);
            j++;
            lastindex = i;
        }
    }
    //处理最后一个子串
    if (lastindex <= strlen(str) - 1) {
        ret[j] = static_cast<char *>(calloc(strlen(str) - lastindex, sizeof(char)));
        memcpy(ret[j], str + lastindex + 1, strlen(str) - 1 - lastindex);
        j++;
    }

    *size = j;

    return ret;
}

void freeExplode(char **arr, int size) {
    int i;
    for (i = 0; i < size; i++) {
        free(arr[i]);
    }

    free(arr);
}